package io.xxx.omni.oss.custom

import com.google.gson.JsonObject
import io.xxx.omni.oss.common.format
import io.xxx.omni.oss.core.PageSynchronizer
import io.xxx.omni.oss.sdk.YjClient
import java.time.LocalDateTime

/**
 * 云集
 */
// http://open.yunjiglobal.com/consoleweb/home
abstract class YjSynchronizer : PageSynchronizer<JsonObject>() {

    protected abstract val method: String

    override fun getResponse(context: Context, pageNo: Int, containsTotal: Boolean): JsonObject {
        val (startTime, endTime, parameter) = context
        val request = buildRequest(startTime, endTime, parameter, pageNo)
        val client = applicationContext.getBean(YjClient::class.java)
        val response = client.execute(store, method, request)
        if (response["flag"].asString == "failure") {
            throwException(context, method, response)
        }
        return response["data"].asJsonObject
    }

    private fun buildRequest(
        startTime: LocalDateTime,
        endTime: LocalDateTime,
        parameter: Any?,
        pageNo: Int,
    ): Map<String, Any> {
        val request = mutableMapOf<String, Any>(
            "query_type" to 1,
            "start_modified" to startTime.format(),
            "end_modified" to endTime.format(),
            "page_no" to pageNo,
            "page_size" to pageSize,
        )
        parameter?.also { request["status"] = it }
        return request
    }
}